<template>
  <el-dialog
    v-model="drawer"
    :title="drawerProps.titles"
    width="400"
    @close="cancel"
  >
    <div class="protocolBody">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
        label-position="left"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="ruleForm.username"
            clearable
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="ruleForm.name"
            clearable
            placeholder="请输入姓名"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="ruleForm.password"
            clearable
            show-password
            type="password"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="passwordAgain">
          <el-input
            placeholder="请输入确认密码"
            v-model="ruleForm.passwordAgain"
            clearable
            show-password
            type="password"
          />
        </el-form-item>
        <!-- <el-form-item label="机器人(个)" prop="robotnum">
            <el-input-number style="width: 100%" v-model="ruleForm.robotnum" :min="1" />
          </el-form-item> -->

        <el-form-item label="入职日期" prop="entrydate">
          <el-date-picker
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            v-model="ruleForm.entrydate"
            type="date"
            placeholder="请选择入职日期"
            style="width: 100%"
          />
        </el-form-item>
        <!-- <el-form-item label="部门" prop="department">
          <el-cascader
            v-model="ruleForm.department"
            :options="departmentOptions"
            :show-all-levels="false"
            style="width: 100%"
            @change="changeDepartment"
            placeholder="请选择部门"
          />
        </el-form-item> -->
        <el-form-item label="角色" prop="roleid">
          <el-select
            v-model="ruleForm.roleid"
            placeholder="请选择角色"
            style="width: 100%"
            clearable
            @change="changeRole"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="启用" prop="isEnable">
            <el-switch v-model="ruleForm.isEnable" />
          </el-form-item> -->
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit(ruleFormRef)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="tsx" name="settingDialog">
import { ref } from "vue";
import {
  createOrganizeApi,
  setuserApi,
  getcontractlistApi,
  uploadImgApi,
} from "@/api/modules/login";

import { ElMessage } from "element-plus";
import { Select } from "@element-plus/icons-vue";
import { reactive } from "vue";
import md5 from "md5";

const drawer = ref(false);
const ruleFormRef = ref();
const pdfShow = ref(false);
const protocolList = ref();
const pdfUrl = ref();
const value = ref("");
const emits = defineEmits(["closeDialog"]);
const currentProtocol = ref<any>({});
const back = () => {
  pdfShow.value = false;
};

const upLoadImgRef = ref();
const selectedDepartments = ref<any>(17);
const departmentOptions = ref([]);
const ruleForm = ref({
  name: "",
  username: "",
  password: "",
  department: "",
  roleid: "",
  robotnum: 0,
  passwordAgain: "",
  entrydate: "",
  avatarurl: "",
  // isEnable: false
});
const options = [
  {
    value: 0,
    label: "业务人员",
  },
  {
    value: 1,
    label: "业务主管",
  },
  {
    value: 2,
    label: "分公司总经理",
  },
  {
    value: 3,
    label: "系统管理员",
  },
];
const closeDialog = () => {
  console.log("关闭弹窗");
  drawer.value = false;
};
const validateText = (rule, value, callback) => {
  console.log("222222222222", value);
  const regex = /^[a-zA-Z0-9\s,.!?;:()"-]+$/; // 定义允许的字符集
  if (!regex.test(value)) {
    callback(new Error("输入内容必须是文字、数字或允许的特殊字符。"));
  } else {
    callback();
  }
};
const changeDepartment = (value: any) => {
  //   console.log("value", value[value.length - 1]);
  ruleForm.value.department = value[value.length - 1];
};
const rules = reactive<any>({
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    // { validator: validateText, trigger: "blur" }、
  ],
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, message: "用户名至少输入2位", trigger: "blur" },
  ],
  // isEnable: [{ required: true, message: "请选择是否启用", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  passwordAgain: [
    { required: true, message: "请输入确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入确认密码"));
        } else if (value !== ruleForm.value.password) {
          callback(new Error("两次输入密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  entrydate: [{ required: true, message: "请选择入职日期", trigger: "change" }],
  department: [{ required: true, message: "请选择部门", trigger: "change" }],
  roleid: [{ required: true, message: "请选择角色", trigger: "change" }],
  robotnum: [
    { required: true, message: "请输入可控制的账号数量", trigger: "change" },
  ],
});

const changeRole = (value: any) => {
  ruleForm.value.roleid = value;
};

/**
 *@use 点击触发上传文件
 */
const changeUploadFiles = (e: any) => {
  uploadFiles(e.target.files);
};
/**
 *@use 点击触发上传文件事件
 */
const upload = async () => {
  // await nextTick();
  upLoadImgRef.value.click();
};
/**
 *@use 上传文件后操作,
 */
const uploadFiles = async (files: any) => {
  console.log("files: ", files);
  // file.value = "";
  const file = files;
  if (!file) {
    ElMessage({
      message: "请先上传文件",
      type: "warning",
    });
    return;
  }

  // 判断是不是图片类型
  const isImage = /image\//.test(file.value[0].type);
  if (!isImage) {
    ElMessage({
      message: "请上传图片类型的文件",
      type: "warning",
    });
    return;
  }

  try {
    const res: any = await uploadImgApi({ file: file[0] });
    if (res.code == 200) {
      ElMessage.success("头像上传成功");
      ruleForm.value.avatarurl = res.data;
    } else {
      ElMessage.warning("系统繁忙，请稍后再试");
    }
  } catch (error) {}
};

const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const par: any = {
          ...ruleForm.value,
          password: md5(ruleForm.value.password),
          department: drawerProps.value.company,
        };

        delete par.passwordAgain;

        console.log("新增用户传参", par);
        const res: any = await setuserApi(par);
        if (res.code == 200) {
          ElMessage({
            message: "新增成功",
            type: "success",
          });
          drawer.value = false;
          resetForm(ruleFormRef.value);
          drawerProps.value.getList();
        } else {
          ElMessage.error("新增失败,请检查网络或联系管理人员");
          return;
        }
      } catch (error) {}
    } else {
      console.log("error submit!", fields);
    }
  });
};

const cancel = () => {
  drawer.value = false;
  resetForm(ruleFormRef.value);
};

/**
 * @use 获取协议列表
 */

const getProtocolList = async () => {
  try {
    const res: any = await getcontractlistApi();
    if (res.code == 200) {
      protocolList.value = res.data;
    }
  } catch (error) {
    ElMessage.error("查询失败,请检查网络或联系管理人员");
  }
};

const toSign = (item: any) => {
  pdfUrl.value = item.filepath;
  pdfShow.value = true;
  currentProtocol.value = item;
};
const resetForm = (formEl: any) => {
  if (!formEl) return;
  formEl.resetFields();
};

const drawerProps = ref<any>({
  isView: false,
  title: "",
  row: {},
});

// 接收父组件传过来的参数
const acceptParams = (params: any) => {
  // getProtocolList();
  // resetForm(ruleFormRef.value);
  drawerProps.value = params;
  drawer.value = true;
  // selectedDepartments.value = params.departmentId;

  console.log("company", drawerProps.value.company);
  ruleForm.value.department = params.departmentId;
  //   console.log("新增用户", drawerProps.value.userManagerList[0].children);
  //   const res = drawerProps.value.userManagerList[0].children.map((item: any) => {
  //     return {
  //       value: item.id,
  //       label: item.title,
  //       children: item.children.map((child: any) => {
  //         return {
  //           value: child.id,
  //           label: child.title,
  //           children: child.children.map((child: any) => {
  //             return {
  //               value: child.id,
  //               label: child.title,
  //               children: child.children.map((child: any) => {
  //                 return {
  //                   value: child.id,
  //                   label: child.title,
  //                 };
  //               }),
  //             };
  //           }),
  //         };
  //       }),
  //     };
  //   });

  //   console.log("res", res);
  //   departmentOptions.value = res;
};

defineExpose({
  acceptParams,
});
</script>
<style lang="scss" scoped>
.userHead {
  position: relative;
  // margin-top: 100px;
  width: 60px;
  height: 60px;
  // background-color: blue;
  // background-color: rgb(255, 254, 254);
  // opacity: .5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  .headimgs {
    width: 100%;
    height: 100%;
  }
  .changeHead {
    // background-color: blue;
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
    color: black;
    display: none;
    font-size: 10px;
  }
}
.userHead:hover {
  cursor: pointer;
  opacity: 0.6;
}
.userHead:hover .changeHead {
  display: block;
}
</style>
